<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="work-order-container">
    <!-- 筛选栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="工单标题">
          <el-input v-model="searchForm.title" placeholder="请输入工单标题" clearable />
        </el-form-item>

        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>

        <el-form-item label="产品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>

        <el-form-item label="工单状态" style="width: 180px;">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="未派单" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已取消" :value="3" />
            <el-option label="已归档" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :picker-options="{ firstDayOfWeek: 1 }"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="fetchWorkOrders">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleArchiveAll" :loading="archiveLoading">一键归档</el-button>
        </el-form-item>
        <el-button type="primary" @click="handleCreate" style="margin-left: auto;">
          <i class="el-icon-plus"></i> 新建工单
        </el-button>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="list-card">
      <el-table
        :data="workOrderList"
        border
        stripe
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="title" label="工单名称" />
        <el-table-column prop="name" label="联系人姓名" />
        <el-table-column prop="phone" label="联系人电话" />
        <el-table-column prop="status" label="工单状态" width="90">
          <template #default="scope">
            <el-tag :type="OrderstatusMap[scope.row.status]?.type">
              {{ OrderstatusMap[scope.row.status]?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="工单类型">
          <template #default="scope">
            <el-tag :type="typeMap[scope.row.type] ? 'success' : 'primary'">
              {{ typeMap[scope.row.type] || scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="经费" />
        <el-table-column label="操作" width="260" align="center">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
              :disabled="scope.row.status === 4"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleChangeStatus(scope.row, 3)"
              :disabled="scope.row.status === 3"
              v-if="scope.row.status !== 2 && scope.row.status !== 3 && scope.row.status !== 4"
            >
              取消
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status !== 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNum"
          :page-sizes="[8, 16, 24]"
          :page-size="pagination.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-if="!loading && total === 0">
        <el-empty description="暂无工单数据" />
      </div>
    </el-card>

    <!-- 工单详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="工单详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-card v-loading="detailLoading">
        <el-descriptions column="1" border class="detail-info">
          <el-descriptions-item label="工单标题">{{ detailData.title }}</el-descriptions-item>
          <el-descriptions-item label="工单描述">{{ detailData.des }}</el-descriptions-item>
          <el-descriptions-item label="联系人姓名">{{ detailData.name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ detailData.phone }}</el-descriptions-item>
          <el-descriptions-item label="联系地址">{{ detailData.address }}</el-descriptions-item>
          <el-descriptions-item label="经费">{{ detailData.money }} 元</el-descriptions-item>

          <el-descriptions-item label="客户信息">
            <div class="customer-info">
              <p><strong>客户名称：</strong>{{ detailData.customerName }}</p>
              <p><strong>联系电话：</strong>{{ detailData.customerPhone }}</p>
              <p><strong>客户地址：</strong>{{ detailData.customerAddress }}</p>
              <p><strong>客户状态：</strong>
                <el-tag :type="detailData.customerStatus === 1 ? 'success' : 'danger'">
                  {{ detailData.customerStatus === 1 ? '正常' : '禁用' }}
                </el-tag>
              </p>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="产品信息">
            <div class="product-info">
              <p><strong>产品名称：</strong>{{ detailData.productName }}</p>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="工单来源">
            {{ typeMap[detailData.type] || '未知来源' }}
          </el-descriptions-item>

          <el-descriptions-item label="支付状态">
            <el-tag :type="payStatusMap[detailData.payStatus]?.type">
              {{ payStatusMap[detailData.payStatus]?.label }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="工单状态">
            <el-tag :type="OrderstatusMap[detailData.status]?.type">
              {{ OrderstatusMap[detailData.status]?.label }}
            </el-tag>
          </el-descriptions-item>

          <!-- 修改图片展示部分 -->
          <el-descriptions-item label="相关图片" v-if="processedImages && processedImages.length > 0">
            <div class="image-list">
              <el-image
                v-for="(image, index) in processedImages"
                :key="index"
                :src="image"
                :preview-src-list="processedImages"
                :initial-index="index"
                style="width: 120px; height: 120px; margin-right: 10px; margin-bottom: 10px;"
                fit="cover"
                lazy
              />
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="调度员">{{ detailData.dispatcherName }}</el-descriptions-item>
          <el-descriptions-item label="接单员">{{ detailData.employeeName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="createOrderVisible"
      title="工单表单"
      :width="600"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <OrderForm :message="currentOrder" @submit-success="handleFormSubmitSuccess" />
    </el-dialog>
  </div>
</template>

<script setup>
import { getWorkOrders, deleteWorkOrder, changeWorkOrderStatus, getWorkOrderDetail, archiveAllCompleted } from '@/api/workOrder';
import { onMounted, reactive, ref, computed } from 'vue';
import OrderForm from './components/WorkOrderForm.vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 类型映射
const typeMap = {
  0: '客户下单',
  1: '系统自建'
};

// 状态映射
const OrderstatusMap = {
  0: { label: '未派单', type: 'warning' },
  1: { label: '进行中', type: 'primary' },
  2: { label: '已完成', type: 'success' },
  3: { label: '已取消', type: 'danger' },
  4: { label: '已归档', type: 'info' }
};

// 支付状态映射
const payStatusMap = {
  0: { label: '未支付', type: 'danger' },
  1: { label: '已支付', type: 'primary' },
  2: { label: '挂账', type: 'warning' },
  3: { label: '免费', type: 'success' }
};

// 工单列表数据
const workOrderList = ref([]);
const createOrderVisible = ref(false);
const loading = ref(false);
const detailLoading = ref(false);
const total = ref(0);
const currentOrder = ref({});
const detailVisible = ref(false);
const detailData = ref({});
const archiveLoading = ref(false);

// 处理图片数据用于展示
const processedImages = computed(() => {
  if (!detailData.value.images) return [];

  let images = detailData.value.images;

  // 如果是字符串，尝试解析为数组
  if (typeof images === 'string') {
    try {
      images = JSON.parse(images);
    } catch (e) {
      images = [images];
    }
  }

  // 确保是数组
  if (!Array.isArray(images)) {
    images = [];
  }

  return images;
});

const handleView = async (row) => {
  try {
    detailLoading.value = true;
    detailVisible.value = true;
    const res = await getWorkOrderDetail(row.id);

    const images = res.data.pic ? res.data.pic.split(',').map(url => url.trim()).filter(Boolean) : [];

    detailData.value = {
      ...res.data,
      images: images
    };
  } catch (error) {
    console.error('获取工单详情失败', error);
    ElMessage.error('获取工单详情失败');
  } finally {
    detailLoading.value = false;
  }
};

// 新建工单
const handleCreate = () => {
  currentOrder.value = {};
  createOrderVisible.value = true;
};

// 编辑工单
const handleEdit = (row) => {
  currentOrder.value = { ...row };
  createOrderVisible.value = true;
};

// 处理表单提交成功
const handleFormSubmitSuccess = () => {
  createOrderVisible.value = false;
  currentOrder.value = {};
  fetchWorkOrders(); // 重新加载列表
};

// 处理弹窗关闭
const handleDialogClose = () => {
  currentOrder.value = {};
};

// 搜索表单
const searchForm = reactive({
  title: '',
  customerName: '',
  productName: '',
  status: null,
  createTime: []
});

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 8
});

// 获取工单列表
const fetchWorkOrders = async () => {
  try {
    loading.value = true;
    const params = {
      pageNo: pagination.pageNum,
      pageSize: pagination.pageSize
    };

    // 手动添加非空参数
    if (searchForm.title) params.title = searchForm.title;
    if (searchForm.customerName) params.customerName = searchForm.customerName;
    if (searchForm.productName) params.productName = searchForm.productName;
    if (searchForm.status !== null) params.status = searchForm.status;

    // 处理时间范围参数
    if (searchForm.createTime && searchForm.createTime.length === 2) {
      const [startDate, endDate] = searchForm.createTime;
      if (startDate && endDate) {
        params.startDate = formatDate(startDate);
        params.endDate = formatDate(endDate);
      }
    }

    const res = await getWorkOrders(params);

    if (res.data && Array.isArray(res.data)) {
      workOrderList.value = res.data;
      total.value = res.data.length;
    } else if (res.data && res.data.records) {
      workOrderList.value = res.data.records;
      total.value = res.data.total || 0;
    } else if (res.data && res.data.list) {
      workOrderList.value = res.data.list;
      total.value = res.data.total || res.data.list.length || 0;
    } else {
      workOrderList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取工单列表失败', error);
    ElMessage.error('获取工单列表失败: ' + (error.message || '未知错误'));
    workOrderList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 日期格式化函数
const formatDate = (date) => {
  if (!date) return '';

  // 如果已经是字符串格式，直接返回
  if (typeof date === 'string') {
    return date;
  }

  // 如果是 Date 对象，格式化为 yyyy-MM-dd
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 取消工单
const handleChangeStatus = async (row, status) => {
  try {
    await ElMessageBox.confirm(
      `确定要${status === 3 ? '取消' : '更改状态'}该工单吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await changeWorkOrderStatus(row.id, status);
    ElMessage.success(`${status === 3 ? '取消' : '状态更改'}成功`);
    fetchWorkOrders(); // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败', error);
      ElMessage.error('操作失败');
    }
  }
};

// 删除工单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该工单吗？删除后无法恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await deleteWorkOrder(row.id);
    ElMessage.success('删除成功');
    fetchWorkOrders(); // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败', error);
      ElMessage.error('删除失败');
    }
  }
};

// 一键归档
const handleArchiveAll = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要将所有已完成状态的工单转为已归档吗？',
      '一键归档确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    archiveLoading.value = true;
    const res = await archiveAllCompleted();

    if (res.code === 200) {
      ElMessage.success('归档成功');
      fetchWorkOrders(); // 重新加载列表
    } else {
      ElMessage.error(res.msg || '归档失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('归档失败: ' + (error.message || '未知错误'));
    }
  } finally {
    archiveLoading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  searchForm.title = '';
  searchForm.customerName = '';
  searchForm.productName = '';
  searchForm.status = null;
  searchForm.createTime = [];
  pagination.pageNum = 1;
  fetchWorkOrders();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.pageNum = 1;
  fetchWorkOrders();
};

const handleCurrentChange = (page) => {
  pagination.pageNum = page;
  fetchWorkOrders();
};

onMounted(() => {
  fetchWorkOrders();
});
</script>

<style scoped>
.work-order-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}

.detail-info {
  margin-bottom: 20px;
}

.customer-info, .product-info {
  line-height: 1.8;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}
</style>
